package net.jjjshop.front;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;

public class WechatStableTokenFetcher {

    public static String getStableAccessToken(String appId, String appSecret, boolean forceRefresh) {
        try {
            String urlStr = "https://api.weixin.qq.com/cgi-bin/stable_token";
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            // 设置请求头，明确请求体是 JSON 格式
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            connection.setDoOutput(true);
            // 设置连接超时和读取超时时间
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            JSONObject requestBody = new JSONObject();
            requestBody.put("appid", appId);
            requestBody.put("secret", appSecret);
            requestBody.put("force_refresh", forceRefresh);

            // 将请求体转换为字节数组并指定编码
            byte[] requestBodyBytes = requestBody.toString().getBytes("UTF-8");
            connection.setRequestProperty("Content-Length", String.valueOf(requestBodyBytes.length));

            DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.write(requestBodyBytes);
            outputStream.flush();
            outputStream.close();

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();

                JSONObject jsonObject = new JSONObject(response.toString());
                if (jsonObject.has("access_token")) {
                    return jsonObject.getString("access_token");
                } else {
                    System.out.println("获取稳定版 access_token 失败: " + jsonObject.toString());
                }
            } else {
                BufferedReader errorReader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
                StringBuilder errorResponse = new StringBuilder();
                String errorLine;
                while ((errorLine = errorReader.readLine()) != null) {
                    errorResponse.append(errorLine);
                }
                errorReader.close();
                System.out.println("请求失败，响应码: " + responseCode + ", 错误信息: " + errorResponse.toString());
            }
        } catch (Exception e) {
            System.err.println("获取稳定版 access_token 时出现异常，请求 URL: https://api.weixin.qq.com/cgi-bin/stable_token，请求体: {\"appid\": \"" + appId + "\", \"secret\": \"" + appSecret + "\", \"force_refresh\": " + forceRefresh + "}");
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        String appId = "wx7b5d529e16c6736b";
        String appSecret = "d6f84c6afc7910845d4cb2f2c0b2a458";
        boolean forceRefresh = false;
        String accessToken = getStableAccessToken(appId, appSecret, forceRefresh);
        if (accessToken != null) {
            System.out.println("获取到的稳定版 access_token: " + accessToken);
        }
    }
}